package offer;

/**
 * @Author Elephas
 * @Date 2022/2/13
 **/
@FunctionalInterface
public interface MaxNumberOfBalloons {
    int maxNumberOfBalloons(String text);
}
class MaxNumberOfBalloonsImpl1 implements MaxNumberOfBalloons{

    char[] dict = new char[]{'b','a','l','o','n'};
    static int[] frequencies = new int[5];

    /**
     * use a table to remember the frequencies of appearance of the each character
     * @param text
     * @return
     */
    @Override
    public int maxNumberOfBalloons(String text) {
        init();
        for (int i = 0; i < text.length(); i++) {
            insert(text.charAt(i));
        }
        return minFreq();
    }
    private void init(){
        for (int i = 0; i < frequencies.length; i++) {
            frequencies[i] = 0;
        }
    }
    private void insert(char c){
        switch (c){
            case 'b': frequencies[0]++; break;
            case 'a': frequencies[1]++; break;
            case 'l': frequencies[2]++; break;
            case 'o': frequencies[3]++; break;
            case 'n': frequencies[4]++; break;
            default: break;
        }
    }
    private int minFreq(){
        // l 和 o 两个字符需要除以二，因为每个单词他们需要出现两次
        frequencies[2] /= 2;
        frequencies[3] /= 2;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < frequencies.length; i++) {
            if(frequencies[i] < min){
                min = frequencies[i];
            }
        }
        return min;
    }
}

class MaxNumberOfBalloonsImpl2 implements MaxNumberOfBalloons{



    /**
     * use a table to remember the frequencies of appearance of the each character
     * @param text
     * @return
     */
    @Override
    public int maxNumberOfBalloons(String text) {
        int[] frequencies = new int[5];
        for (int i = 0; i < frequencies.length; i++) {
            frequencies[i] = 0;
        }
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            switch (c){
                case 'b': frequencies[0]++; break;
                case 'a': frequencies[1]++; break;
                case 'l': frequencies[2]++; break;
                case 'o': frequencies[3]++; break;
                case 'n': frequencies[4]++; break;
                default: break;
            }
        }
        frequencies[2] /= 2;
        frequencies[3] /= 2;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < frequencies.length; i++) {
            if(frequencies[i] < min){
                min = frequencies[i];
            }
        }
        return min;
    }
}
